package com.huatai.bi.config;

import com.huatai.common.entity.UserInfo;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.CollectionUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.annotation.WebListener;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;


/**
 * @program: ganghua
 * @description: ws配置
 * @author: songxiude
 * @create: 2024-09-19 09:33
 **/
@Component
@Configuration
@WebListener
@Slf4j
public class WebSocketConfig extends ServerEndpointConfig.Configurator{
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}

//	@Override
//	public boolean checkOrigin(String originHeaderValue) {
//		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//		String token = servletRequestAttributes.getRequest().getHeader("Sec-WebSocket-Protocol");
//		if(StringUtil.isEmpty(token)){
//			return false;
//		}
//		UserInfo userInfo = AuthUtil.parseUser(token);
//		if(ObjectUtil.isEmpty(userInfo)){
//			return false;
//		}
//		return true;
//	}

	@Override
	public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
		List<String> list = request.getHeaders().get("Sec-WebSocket-Protocol");
		response.getHeaders().put("Sec-WebSocket-Protocol",list);
		if(CollectionUtil.isEmpty(list)){
			return;
		}
		String token = list.get(0);
		if(StringUtil.isEmpty(token)){
			return;
		}
		//Claims claims = AuthUtil.getClaims(token);
		UserInfo userInfo = AuthUtil.parseUser(token);
		if(ObjectUtil.isEmpty(userInfo)){
			return;
		}
		log.info("ws连接成功");
	}

//	@Override
//	public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
//		return super.getEndpointInstance(clazz);
//	}
}
